package com.drinks.yiniang.ui.activity.community;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.listview.UploadCommunityGridAdapter;
import com.drinks.yiniang.common.camera.album.entity.GoodsTagPoints;
import com.drinks.yiniang.common.camera.album.entity.TagPoints;
import com.drinks.yiniang.entity.common.UploadImageJson;
import com.drinks.yiniang.entity.community.CommunityGoodsConfig;
import com.drinks.yiniang.entity.community.CommunityTopicJson;
import com.drinks.yiniang.entity.event.CommunityPublishEvent;
import com.drinks.yiniang.entity.event.PayWXEventBus;
import com.drinks.yiniang.io.api.CommonApiIO;
import com.drinks.yiniang.io.api.CommunityApiIO;
import com.drinks.yiniang.io.http.ProgressRequestBody;
import com.drinks.yiniang.ui.activity.camera.CameraActivity;
import com.drinks.yiniang.utils.FileUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnListItemClickListener;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.pickerimage.activity.PicturePreviewActivity;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.layout.TextEditArrowLayout;
import com.hansen.library.ui.widget.layout.TextTextArrowLayout;
import com.hansen.library.ui.widget.listview.NoScrollGridView;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.StringUtils;
import com.hansen.library.utils.TimeUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 发布动态
 *
 * @author han
 * @date 2019/09/10
 */
public class CommunityPublishActivity extends BaseTranBarActivity implements OnNavgationBarClickListener,
        AdapterView.OnItemClickListener, OnListItemClickListener {

    private final int REQ_ADD_TOPIC_CODE = 0x01;//添加话题
    private final int REQ_ADD_MFRS_CODE = 0x02;//添加厂商
    private final int UPLOAD_MAX_NUM = 5;//上传图片最大数量

    //nav
    private NavigationBarLayout nav_bar_community_publish;
    //pic 列表
    private NoScrollGridView gv_c_publish_pic;
    //标题
    private EditText et_c_publish_title;
    //描述
    private EditText et_c_publish_des;
    //话题
    private TextEditArrowLayout ll_c_publish_topic;
    //添加厂商
    private TextTextArrowLayout ll_c_publish_firm;
    //存草稿
    private TextView tv_c_publish_save_drafts;
    //发布
    private Button btn_c_publish;

    private UploadCommunityGridAdapter mUploadImageGridAdapter;

    private List<UploadImageJson.UploadImageData> mImageList;
    private List<UploadImageJson.UploadImageData> mUnLoadImageList;

    private File mFile;

    //关联的商品id [{"goods_id":1,"image_id":1,"width":400,"height":300,"x":200,"y":100}]
    private List<CommunityGoodsConfig> mGoodsListJson;
    //话题，多个以|分开
    private List<String> mTopicList;
    //厂商品牌id
    private String mMfrsBrandId;
    //状态 1发布 0草稿
    private String mStatus;

    @Override
    protected void initView() {
        nav_bar_community_publish = findViewById(R.id.nav_bar_community_publish);

        gv_c_publish_pic = findViewById(R.id.gv_c_publish_pic);

        et_c_publish_title = findViewById(R.id.et_c_publish_title);
        et_c_publish_des = findViewById(R.id.et_c_publish_des);

        ll_c_publish_topic = findViewById(R.id.ll_c_publish_topic);
        ll_c_publish_firm = findViewById(R.id.ll_c_publish_firm);

        tv_c_publish_save_drafts = findViewById(R.id.tv_c_publish_save_drafts);

        btn_c_publish = findViewById(R.id.btn_c_publish);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        mImageList = new ArrayList<>();
        mGoodsListJson = new ArrayList<>();
        mTopicList = new ArrayList<>();

        mUploadImageGridAdapter = new UploadCommunityGridAdapter(mContext, mImageList);

        gv_c_publish_pic.setAdapter(mUploadImageGridAdapter);

        //上传图片
        doUploadFile(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);

        //上传图片
        doUploadFile(intent);
    }

    @Override
    protected void initListener() {
        nav_bar_community_publish.setOnNavgationBarClickListener(this);
        ll_c_publish_topic.setOnClickListener(this);
        ll_c_publish_firm.setOnClickListener(this);
        tv_c_publish_save_drafts.setOnClickListener(this);
        btn_c_publish.setOnClickListener(this);

        gv_c_publish_pic.setOnItemClickListener(this);
        mUploadImageGridAdapter.setOnListItemClickListener(this);
    }

    @Override
    public void widgetClick(View v) {
        Intent mIntent;

        switch (v.getId()) {
            case R.id.ll_c_publish_topic://添加话题
                mIntent = new Intent(mContext, TopicListActivity.class);
                mIntent.putExtra(Constants.KeyType, TopicListActivity.TYPE_TOPIC_LIST);
                startActivityForResult(mIntent, REQ_ADD_TOPIC_CODE);
                break;
            case R.id.ll_c_publish_firm://添加厂商
                mIntent = new Intent(mContext, TopicListActivity.class);
                mIntent.putExtra(Constants.KeyType, TopicListActivity.TYPE_MFRS_BRAND_LIST);
                startActivityForResult(mIntent, REQ_ADD_MFRS_CODE);
                break;
            case R.id.tv_c_publish_save_drafts://存草稿
                mStatus = "0";
                doSaveDrafts();
                break;
            case R.id.btn_c_publish://发布
                mStatus = "1";
                doPublish();
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_community_publish;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (view.getId() == R.id.fl_grid_add_c_pic) {
            startActivity(new Intent(mContext, CameraActivity.class));
        } else {
            preview(position);
        }
    }

    @Override
    public void onItemClick(View mView, int position) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == Constants.RESULT_CODE_NORMAL && intent != null) {
            switch (requestCode) {
                case REQ_ADD_TOPIC_CODE://添加话题
                    CommunityTopicJson.TopicList topic = (CommunityTopicJson.TopicList) intent.getSerializableExtra(Constants.KeyObject);

                    if (topic != null) {
                        mTopicList.add(topic.getName());

                        StringBuilder topicBuild = new StringBuilder();

                        for (int i = 0; i < mTopicList.size(); i++) {
                            if (i == mTopicList.size() - 1) {
                                topicBuild.append(mTopicList.get(i));
                            } else {
                                topicBuild.append(mTopicList.get(i));
                                topicBuild.append("|");
                            }
                        }

                        ll_c_publish_topic.setArrowText(topicBuild.toString());
                    }
                    break;
                case REQ_ADD_MFRS_CODE://添加厂商
                    CommunityTopicJson.TopicList data = (CommunityTopicJson.TopicList) intent.getSerializableExtra(Constants.KeyObject);

                    if (data != null) {
                        mMfrsBrandId = data.getId();
                        ll_c_publish_firm.setArrowText(data.getName());
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void preview(int position) {
        if (CommonUtils.isArrayIndexOutOfBounds(mImageList, position)) {
            return;
        }

        List<String> urlList = new ArrayList<>();

        for (int i = 0; i < mImageList.size(); i++) {
            urlList.add(mImageList.get(i).getOriginal());
        }

        Intent mIntent = new Intent(mContext, PicturePreviewActivity.class);
        mIntent.putExtra(Constants.KeyPos, position);

        mIntent.putStringArrayListExtra(Constants.KeyUrl, (ArrayList<String>) urlList);

        startActivity(mIntent);
    }

    //发布动态
    private void doPublish() {
        StringBuilder builder = new StringBuilder();

        mGoodsListJson.clear();

        CommunityGoodsConfig goodsConfig;
        UploadImageJson.UploadImageData imgData;
        TagPoints tagPoints;

        for (int i = 0; i < mImageList.size(); i++) {
            imgData = mImageList.get(i);

            if (imgData.getTagPoints() != null) {
                for (int j = 0; j < imgData.getTagPoints().size(); j++) {
                    goodsConfig = new CommunityGoodsConfig();

                    tagPoints = imgData.getTagPoints().get(j);

                    goodsConfig.setGoods_id(tagPoints.getGoodsId());
                    goodsConfig.setImage_id(imgData.getId());
                    goodsConfig.setWidth(imgData.getWdith());
                    goodsConfig.setHeight(imgData.getHeight());
                    goodsConfig.setX(tagPoints.getX());
                    goodsConfig.setY(tagPoints.getY());

                    mGoodsListJson.add(goodsConfig);
                }
            }

            if (!StringUtils.isEmpty(imgData.getId())) {
                if (i == (mImageList.size() - 1)) {
                    builder.append(imgData.getId());
                } else {
                    builder.append(imgData.getId());
                    builder.append(",");
                }
            }
        }

        String title = StringUtils.getEditTextString(et_c_publish_title.getText());

        if (StringUtils.isEmpty(title)) {
            ToastUtils.showShort(R.string.text_hint_input_title);
            return;
        }

        String content = StringUtils.getEditTextString(et_c_publish_des.getText());

        if (StringUtils.isEmpty(content)) {
            ToastUtils.showShort(R.string.text_hint_fill_in_more_des);
            return;
        }

        StringBuilder topicBuild = new StringBuilder();

        for (int i = 0; i < mTopicList.size(); i++) {
            if (i == mTopicList.size() - 1) {
                topicBuild.append(mTopicList.get(i));
            } else {
                topicBuild.append(mTopicList.get(i));
                topicBuild.append("|");
            }
        }

        if (!StringUtils.isEmpty(ll_c_publish_topic.getEditText())) {
            topicBuild.append(topicBuild.length() > 0 ? "|" : "");
            topicBuild.append(ll_c_publish_topic.getEditText());
        }

        if (topicBuild.length() <= 0) {
            ToastUtils.showShort(R.string.text_hint_input_topic);
            return;
        }

        if (StringUtils.isEmpty(mMfrsBrandId)) {
            ToastUtils.showShort(R.string.text_add_manufacturer);
            return;
        }

        String goodsJson = JSON.toJSONString(mGoodsListJson);

        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityPublish(title, content, mStatus, goodsJson, builder.toString(),
                topicBuild.toString(), mMfrsBrandId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
                    @Override
                    public void onSuccess(BaseJson res) {
                        ToastUtils.showShort(R.string.text_publish_success);
                        EventBus.getDefault().post(new CommunityPublishEvent());
                        finish();
                    }

                    @Override
                    public void onError(Tuple2<Integer, String> error) {
                        ToastUtils.showShort(error._2);
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }
                });
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            dismissDialog();
            ToastUtils.showShort(msg.what == 0x01 ? R.string.text_save_success : R.string.text_save_fail);
        }
    };

    private void doSaveDrafts() {
        if(CommonUtils.isEmptyList(mImageList)) {
            return;
        }

        showLoadingDialog();

        new Thread(new Runnable() {
            @Override
            public void run() {
                UploadImageJson.UploadImageData imgData;
                try {
                    boolean isSaveSuccess = false;

                    for (int i = 0; i < mImageList.size(); i++) {
                        imgData = mImageList.get(i);

                        if (!StringUtils.isEmpty(imgData.getAbsolutePath())) {
                            if(FileUtils.isExistDirOrMkdirs(Constants.RootDrafts)) {
                                FileUtils.copyFile(imgData.getAbsolutePath(), Constants.RootDrafts + TimeUtil.getCurrentTimeMillis() + i + ".png");
                                isSaveSuccess = true;
                            }
                        }
                    }

                    mHandler.sendEmptyMessage(isSaveSuccess ? 0x01 : 0x02);
                } catch (IOException e) {
                    mHandler.sendEmptyMessage(0x02);
                    LogUtils.e("copy file error " + e.toString());
                }
            }
        }).start();
    }

    private void doUploadFile(Intent data) {
        if(data == null) {
            return;
        }

        mUnLoadImageList = (List<UploadImageJson.UploadImageData>) data.getSerializableExtra(Constants.KeyList);

        if(mUnLoadImageList == null) {
            return;
        }

        if(mImageList == null) {
            mImageList = new ArrayList<>();
        }

        mImageList.clear();

        if (CommonUtils.isEmptyList(mUnLoadImageList)) {
            ToastUtils.showShort("暂无选择的图片");
            return;
        }

        showLoadingDialog(R.string.text_uploading_dot);

        uploadFile();
    }

    //上传图片
    private void uploadFile() {
        final UploadImageJson.UploadImageData pathData = mUnLoadImageList.get(0);

        if (pathData.getAbsolutePath() == null) {
            dismissDialog();
            return;
        }

        mFile = new File(pathData.getAbsolutePath());

        if (mFile == null) {
            dismissDialog();
            return;
        }

        CommonApiIO.getInstance().uploadImage(mFile, new ProgressRequestBody.ProgressListener() {
            @Override
            public void onProgress(long totalSize, long currSize, boolean done, int id) {

            }
        }, new APIRequestCallback<UploadImageJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(UploadImageJson res) {
                if (mImageList == null) {
                    dismissDialog();
                    return;
                }

                UploadImageJson.UploadImageData uploadImageData = res.getData();

                uploadImageData.setTagPoints(pathData.getTagPoints());
                uploadImageData.setAbsolutePath(pathData.getAbsolutePath());
                uploadImageData.setName(pathData.getName());
                uploadImageData.setWdith(pathData.getWdith());
                uploadImageData.setHeight(pathData.getHeight());

                mImageList.add(uploadImageData);

                mUploadImageGridAdapter.notifyDataSetChanged();

                mUnLoadImageList.remove(0);

                if (mImageList.size() == UPLOAD_MAX_NUM || CommonUtils.isEmptyList(mUnLoadImageList)) {
                    dismissDialog();
                    return;
                }

                uploadFile();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                dismissDialog();
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    @Override
    protected void onDestroy() {
        if(mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        super.onDestroy();
    }
}
